//用户调用方法----------------begin
//绑定并返回的属性
var userEmailObj = {};
var commonFunction = initCommonFunction();


/**
 * 修改审批流 初始化 审批流方法
 * @param approvers
 * @returns {{result: (function(): {approvers: Array, userInfos: Array})}}
 */
function initApprovalByDatas(approvers,isSubmit) {
    function getCloneDatas(ids) {
        var result=[];
        ids.forEach(function (e) {
            var clone = $("#" + e).clone(true);
            clone.removeAttr("id");
            result.push(clone)
        })
       return result;
    }

    function initApprovalByApprovers(approvers) {
        var approver_config = $("#approver_config")
        approver_config.empty();
        if (!approvers) {
            return
        }

        var models = getCloneDatas(["approval_approver_now","approval_approver_default","approval_approver_passed","approval_approver_error"])
        models.forEach(function (e, n) {
            if (n == 0) {
                $(e).find(".approval_approver").css("background-color", "#00FF00");
            }
            if ($(e).hasClass("not_default_node")) {
                $(e).find(".img_top").css("display", "none")
            }
        })

        approvers.forEach(function (e, n) {
            var node = $(models[e.status + 1]).clone(true);
            if (n == 0) {
                node.find(".approval_step").remove()
            }

            commonFunction.initApproverNodeData(node, e,isSubmit)

            approver_config.append(node);
        })
        approver_config.find(".not_default_node:last .img_top").removeAttr("style")
    }

    initApprovalByApprovers(approvers);

    return {
        result: function () {
            var result = {approvers: [], userInfos: []};
            $("#approver_config .approval_approver_body:not([isApplyUser])").each(function () {
                var userId = $(this).attr("ehr_id"),userObj = eval("("+$(this).attr("user_json")+")"),email = $(this).attr("email");
                userObj["email"]=email;
                userObj["changeEmail"]==userEmailObj.hasOwnProperty(userId);
                result.approvers.push(userId);
                result.userInfos.push(userObj);
            });
            return result;
        }
    }
}

/**
 * 初始化提交审批流方法
 * @param applyUserName
 */
function initSubmitApproval(applyUserName) {
    var results = [{userName: applyUserName, status: 1, isApplyUser: true}];

    var approvers= commonFunction.getFirstApprover();
    if(approvers&&approvers[0]){
        approvers[0]["status"]=0;
        results.push(approvers[0])
    }

    commonFunction.getSuperiors().forEach(function (e) {
        results.push(e)
    })
    return initApprovalByDatas(results,true)
}
//用户调用方法----------------end

$(document).ready(function () {
    $("#userNameId").keydown(function(event){
        if(event.which==13){
            $("#searchUserId").click();
        }
    });
    $("#searchUserId").click(function () {
        function callBackFunc(result) {
            $('#choose_approver_select .select-option').remove();

            var option_hide = $('#choose_approver_select .select-option-hide');

            var option = option_hide.clone(true);
            option.removeClass("select-option-hide").addClass("select-option").show();

            result.forEach(function (e) {
                var option_add = option.clone(true);
                option_add.html(e.userName + (commonFunction.isNotBlank(e.departmentName) ? ("(" + e.departmentName + ")") : ""));
                commonFunction.setNodeDataFromOpt(option_add, e);
                option_add.insertBefore(option_hide);
            })
        }

        if($("#approver_config .approval_approver_body:not([isApplyUser])").length==0||$("#approver_config .node_choosed").closest(".approval_approver_body").index()==1){
            callBackFunc(commonFunction.getFirstApprover());
        }else{
            commonFunction.getUserByFuzzy($("#userNameId").val(),callBackFunc);
        }
    })

    $("#add_label_button").click(function () {
        var selectedOption = commonFunction.returnSelectedData(true);
        var node = commonFunction.getCloneData("approval_approver_default");
        if (selectedOption == null || !selectedOption.clicked || $("#approver_config .approval_approver_body:last").attr("ehr_id") == selectedOption.ehr_id) {
            node.find(".approver_name_class").html("待添加");
        }else {
            commonFunction.changeApproverNodeData(node,selectedOption);
        }

        $("#approver_config").append(node)
        node.find(".approval_approver").click();
    })

    $("#choose_approver_select dd").click(function () {
        $(this).addClass("option-clicked");
        if (!$(this).hasClass("layui-this")) {
            $("#choose_approver_select .select-option-div .layui-this").removeClass("layui-this");
            $(this).addClass("layui-this");
        }

        var nodes = $("#approver_config .node_choosed").closest(".approval_approver_body");
        var selectedOption = commonFunction.returnSelectedData();
        if (nodes.length == 1 && selectedOption != null) {
            commonFunction.changeApproverNodeData(nodes,selectedOption);
        }
    })

    $(".approval_approver_body .img_top").click(function () {
        var approval_approver_body = $(this).closest(".approval_approver_body")
        var node = commonFunction.getCloneData("approval_approver_default");
        node.find(".approver_name_class").html("待添加");
        node.insertAfter(approval_approver_body);
    })

    $(".approval_approver_body .img_bottom").click(function () {
        $(this).closest(".approval_approver_body").remove();
    })
    $(".approval_approver_body .img_email").click(function () {
        var node= $(this).closest(".approval_approver_body");
        var email=node.attr("email"),ehr_id=node.attr("ehr_id");
        if (commonFunction.isBlank(email)) {
            layer.prompt({
                formType: 0,
                value: '',
                title: '请输入邮箱',
                area: ['800px', '350px'] //自定义文本域宽高
            }, function (value, index, elem) {
                if (!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(value)) {
                    layer.msg('邮箱格式错误！');
                } else {
                    layer.close(index);
                    node.attr("email",value);
                    userEmailObj[ehr_id]=value;
                }
            });
        } else{
            layer.prompt({
                formType: 0,
                value: email,
                title: '请修改邮箱',
                area: ['800px', '350px'] //自定义文本域宽高
            }, function (value, index, elem) {
                if (!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(value)) {
                    layer.msg('邮箱格式错误！');
                } else {
                    layer.close(index);
                    node.attr("email",value);
                    userEmailObj[ehr_id]=value;
                }
            });
        }
    })

    $("#approval_approver_default .approval_approver").click(function () {
        $("#approver_config .node_choosed").removeClass("node_choosed");
        $(this).addClass("node_choosed");
    })
})

function initCommonFunction() {
    var result={},func=getApprovalCommonFunc();
    var nodeAttr={user_id:function(e){return e.id},ehr_id: function(e){return e.ehrId}, userName: function(e){return e.userName},title: function(e){return e.userName + (commonFunction.isNotBlank(e.departmentName) ? ("(" + e.departmentName + ")") : "")},email:function(e){return e.email},user_json:function(e){return JSON.stringify(e)}}

    result.getUserByFuzzy=function(userName,callBackFunc) {
        return func.getUserByFuzzy(userName,callBackFunc)
    }
    result.getFirstApprover = function () {
        return func.getFirstApprover()
    }
    result.getSuperiors = function () {
        return func.getSuperiors()
    }
    result.returnSelectedData=function(ifClicked) {
        var selectedOption = $("#choose_approver_select .layui-this");

        if (selectedOption.length != 1) {
            return null;
        }

        var nodeData = commonFunction.getNodeData(selectedOption);

        if (commonFunction.isBlank(nodeData.ehr_id)) {
            return null;
        }

        if (ifClicked) {
            var clicked = selectedOption.hasClass("option-clicked");
            selectedOption.removeClass("option-clicked");
            nodeData["clicked"]=clicked;
        }
        return nodeData;
    }
    result.initApproverNodeData=function(approverNode, data,isSubmit) {
        approverNode.find(".approver_name_class").html(data.userName);
        if(data.isApplyUser){
            approverNode.attr("isApplyUser", true)
        }else if(isSubmit){
            if(commonFunction.isBlank(data.email)){
                approverNode.find(".img_email").closest("div").show();
                approverNode.find(".approver_name_class").css({"padding-left":"0px"})
            }else{
                approverNode.find(".img_email").closest("div").hide();
                approverNode.find(".approver_name_class").css({"padding-left":"10px"})
            }
            commonFunction.setNodeDataFromOpt(approverNode,data);
        }else {
            commonFunction.setNodeDataFromOpt(approverNode,data);
        }
    }
    result.changeApproverNodeData=function(approverNode, data) {
        approverNode.find(".approver_name_class").html(data.userName);
        if(data.isApplyUser){
            approverNode.attr("isApplyUser", true)
        }else {
            if(commonFunction.isNotBlank(data.user_id)||commonFunction.isBlank(data.email)){
                approverNode.find(".img_email").closest("div").show();
                approverNode.find(".approver_name_class").css({"padding-left":"0px"})
            }else{
                approverNode.find(".img_email").closest("div").hide();
                approverNode.find(".approver_name_class").css({"padding-left":"10px"})
            }
            if(userEmailObj.hasOwnProperty(data.ehr_id)){
                data.email=userEmailObj[data.ehr_id];
            }
            commonFunction.setNodeData(approverNode,data);
        }
    }
    result.getCloneData=function(id) {
        var clone = $("#" + id).clone(true);
        clone.removeAttr("id");
        return clone;
    }
    result.isNotBlank=function(s) {
        return s != undefined && s != null && (s + "").trim().length > 0
    }
    result.isBlank=function(s) {
        return !result.isNotBlank(s)
    }
    result.setNodeDataFromOpt=function (node,data) {
        for(var name in nodeAttr){
            node.attr(name,nodeAttr[name](data))
        }
    }
    result.setNodeData=function (node,data) {
        for(var name in nodeAttr){
            node.attr(name,data[name])
        }
    }
    result.getNodeData=function(node){
        var data={};
        for(var name in nodeAttr){
            data[name]= node.attr(name);
        }
        return data;
    }
    return result;
}





<!--调用示例-->
// var approvers = [
// {userId:"DDD",userName: "申请人",status: 1,isApplyUser:true},
// {userId:"EEE",userName: "shenpiren1",status: 0},
// {userId:"XXX",userName: "sdfa",status: 2}]
//
// initEdirApprover(approvers);
//
// 返回配置结果
// returnApprovers()